
package com.tocea.formation.users.library.rent;


import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import com.tocea.formation.exceptions.NotEnoughtExemplaireException;
import com.tocea.formation.exceptions.NotSuchRentException;
import com.tocea.formation.library.IBook;
import com.tocea.formation.library.ILibrary;
import com.tocea.formation.library.IRentManager;
import com.tocea.formation.library.Libraryfactory;
import com.tocea.formation.users.IUser;

public class RentManager implements IRentManager
{
    
    private static long          nbRent = 0;
    
    private final ILibrary       library;
    private final Set<IRentBook> rents;
    
    public RentManager(ILibrary library) {
    
        super();
        this.library = library;
        rents = new HashSet<IRentBook>();
    }
    
    public void rentBook(IUser _user, IBook _book) throws NotEnoughtExemplaireException {
    
        nbRent++;
        IRentBook rent = Libraryfactory.INSTANCE.createRentBook(_user, _book, nbRent);
        rents.add(rent);
        _user.addRent(rent);
        library.removeExemplaires(_book, 1);   
    }
    
    public void returnBook(IRentBook _rent) throws NotSuchRentException {
    
        if (rents.contains(_rent)) {
            throw new NotSuchRentException("this rent does not exist");
        }
        _rent.setreturnDate(new Date());
        library.addExemplaires(_rent.getBook(), 1);
        
    }
    
    public void returnBook(long _idRent) throws NotSuchRentException {
    
        boolean find = false;
        for (Iterator<IRentBook> iterator = rents.iterator(); !find && iterator.hasNext();) {
            IRentBook rent = iterator.next();
            if (rent.getId() == _idRent) {
                find = true;
                rent.setreturnDate(new Date());
                library.addExemplaires(rent.getBook(), 1);
            }           
        }
        if (!find) {
            throw new NotSuchRentException("this rent does not exist");
        }
        
    }
    
    public Set<IRentBook> getAllRents() {
    
        return rents;
    }
    
}
